package com.gqj.elec.controller;

import com.alibaba.fastjson2.JSON;
import com.gqj.common.annotation.Log;
import com.gqj.common.constant.UserConstants;
import com.gqj.common.core.controller.BaseController;
import com.gqj.common.core.domain.AjaxResult;
import com.gqj.common.core.page.TableDataInfo;
import com.gqj.common.enums.BusinessType;
import com.gqj.common.utils.StorageUtil;
import com.gqj.common.utils.poi.ExcelUtil;
import com.gqj.common.utils.sign.Base64;
import com.gqj.elec.domain.ElecMaterialOutdetail;
import com.gqj.elec.domain.ElecMaterialOutinfo;
import com.gqj.elec.domain.vo.ElecMaterialOutinfoVo;
import com.gqj.elec.service.IElecMaterialOutdetailService;
import com.gqj.elec.service.IElecMaterialOutinfoService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.imageio.stream.FileImageInputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

/**
 * 物资出库Controller
 *
 * @author lxq
 * @date 2023-12-17
 */
@RestController
@RequestMapping("/elec/elecMaterialOutinfo")
public class ElecMaterialOutinfoController extends BaseController {
    @Autowired
    private IElecMaterialOutinfoService elecMaterialOutinfoService;
    @Autowired
    private IElecMaterialOutdetailService elecMaterialOutdetailService;
    @Value("${downloadPath}")
    private String downloadPath;

    /**
     * 查询物资出库列表
     */
    @PreAuthorize("@ss.hasPermi('elec:elecMaterialOutinfo:list')")
    @GetMapping("/list")
    public TableDataInfo list(ElecMaterialOutinfo elecMaterialOutinfo) {
        startPage();
        elecMaterialOutinfo.setDelFlag("0");
        List<ElecMaterialOutinfo> list = elecMaterialOutinfoService.selectElecMaterialOutinfoList(elecMaterialOutinfo);
        return getDataTable(list);
    }

    /**
     * 导出物资出库列表
     */
    @PreAuthorize("@ss.hasPermi('elec:elecMaterialOutinfo:export')")
    @Log(title = "物资出库", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ElecMaterialOutinfo elecMaterialOutinfo) {
        elecMaterialOutinfo.setDelFlag("0");
        List<ElecMaterialOutinfo> list = elecMaterialOutinfoService.selectElecMaterialOutinfoList(elecMaterialOutinfo);
        ExcelUtil<ElecMaterialOutinfo> util = new ExcelUtil<ElecMaterialOutinfo>(ElecMaterialOutinfo.class);
        util.exportExcel(response, list, "物资出库数据");
    }

    /**
     * 获取物资出库详细信息
     */
    @PreAuthorize("@ss.hasPermi('elec:elecMaterialOutinfo:query')")
    @GetMapping(value = "/{outId}")
    public AjaxResult getInfo(@PathVariable("outId") Long outId) {
        return AjaxResult.success(elecMaterialOutinfoService.selectElecMaterialOutinfoByOutId(outId));
    }

    /**
     * 新增物资出库
     */
    @PreAuthorize("@ss.hasPermi('elec:elecMaterialOutinfo:add')")
    @Log(title = "物资出库", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ElecMaterialOutinfo elecMaterialOutinfo) {
        if (null == elecMaterialOutinfo.getElecMaterialList() || elecMaterialOutinfo.getElecMaterialList().size() <= 0) {
            return AjaxResult.error("工器具列表为空，不允许新增");
        }
        elecMaterialOutinfo.setCreateBy(getUsername());
        return toAjax(elecMaterialOutinfoService.insertElecMaterialOutinfo(elecMaterialOutinfo));
    }

    /**
     * 修改物资出库
     */
    @PreAuthorize("@ss.hasPermi('elec:elecMaterialOutinfo:edit')")
    @Log(title = "物资出库", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ElecMaterialOutinfo elecMaterialOutinfo) {
        ElecMaterialOutinfo temp = elecMaterialOutinfoService.selectElecMaterialOutinfoByOutId(elecMaterialOutinfo.getOutId());
        if (!UserConstants.BILL_ISDEL.equals(temp.getOutStatus())) {
            return AjaxResult.error("单据不是录入状态，不允许修改");
        }
        if (null == elecMaterialOutinfo.getElecMaterialList() || elecMaterialOutinfo.getElecMaterialList().size() <= 0) {
            return AjaxResult.error("工器具列表为空，不允许修改");
        }
        elecMaterialOutinfo.setUpdateBy(getUsername());
        return toAjax(elecMaterialOutinfoService.updateElecMaterialOutinfo(elecMaterialOutinfo));
    }

    /**
     * 删除物资出库
     */
    @PreAuthorize("@ss.hasPermi('elec:elecMaterialOutinfo:remove')")
    @Log(title = "物资出库", businessType = BusinessType.DELETE)
    @DeleteMapping("/{outIds}")
    public AjaxResult remove(@PathVariable Long[] outIds) {
        for (Long outId : outIds) {
            ElecMaterialOutinfo temp = elecMaterialOutinfoService.selectElecMaterialOutinfoByOutId(outId);
            if (!UserConstants.BILL_ISDEL.equals(temp.getOutStatus())) {
                return AjaxResult.error("单据" + temp.getBatchNumber() + "不是录入状态，不允许删除");
            }
        }
        return toAjax(elecMaterialOutinfoService.deleteElecMaterialOutinfoByOutIds(outIds));
    }

    /**
     * 查看照片
     */
    @GetMapping("/searchImg")
    public AjaxResult searchImg(ElecMaterialOutinfo elecMaterialOutinfo) {

        ElecMaterialOutinfo entity = elecMaterialOutinfoService.selectElecMaterialOutinfoByOutId(elecMaterialOutinfo.getOutId());
        if (null == entity.getFacePicuture() || "".equals(entity.getFacePicuture())) {
            return AjaxResult.success(entity);
        }

        String path = "D:/gwelec-zp/" + entity.getFacePicuture();
        byte[] data = null;
        FileImageInputStream input = null;
        try {
            input = new FileImageInputStream(new File(path));
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            byte[] buf = new byte[1024];
            int numBytesRead = 0;
            while ((numBytesRead = input.read(buf)) != -1) {
                output.write(buf, 0, numBytesRead);
            }
            data = output.toByteArray();
            output.close();
            input.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        entity.setFacePicuture("data:image/gif;base64," + Base64.encode(data));
        return AjaxResult.success(entity);
    }

    /**
     * 下载工器具json文件
     */
    @ApiOperation("下载工器具json文件")
    @PreAuthorize("@ss.hasPermi('elec:elecMaterialOutinfo:downloadJsonElecMaterialOutInfo')")
    @GetMapping("/downloadJsonElecMaterialOutInfo")
    public AjaxResult downloadJsonElecMaterialOutInfo(ElecMaterialOutinfo elecMaterialOutinfo) {
        elecMaterialOutinfo.setDelFlag("0");
        List<ElecMaterialOutinfo> mt = elecMaterialOutinfoService.selectElecMaterialOutinfoList(elecMaterialOutinfo);
        ElecMaterialOutdetail elecMaterialOutdetail = new ElecMaterialOutdetail();

        for (ElecMaterialOutinfo elecMaterialOutinfoTemp : mt) {
            elecMaterialOutdetail.setOutId(elecMaterialOutinfoTemp.getOutId());
            elecMaterialOutinfoTemp.setElecMaterialOutdetailList(elecMaterialOutdetailService.selectElecMaterialOutdetailList(elecMaterialOutdetail));
        }

        List<ElecMaterialOutinfoVo> vos = StorageUtil.copyList(mt, ElecMaterialOutinfoVo::new);

        String orderNo = "工器具出库任务数据" + StorageUtil.getOrderNoTo12();
        String fileName = downloadPath + orderNo + ".json";
        String jsonStringAc = JSON.toJSONString(vos);
        File file = new File(fileName);
        try (FileWriter fileWriter = new FileWriter(file)) {
            fileWriter.write(jsonStringAc);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return AjaxResult.success(fileName);
    }
}
